import { Router } from '@angular/router';
import { UserService } from './../service/user.service';
import { RequestService } from './../service/service.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-update-password',
  templateUrl: './update-password.component.html',
  styleUrls: ['./update-password.component.scss']
})
export class UpdatePasswordComponent implements OnInit {

  constructor(private fb: FormBuilder,
    private changePW: RequestService,
    private user: UserService,
    private message: NzMessageService,
    private router: Router) { }
  validateForm: FormGroup;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    // 验证通过提交表单
    if (this.validateForm.valid) {

      const obj = {
        username: JSON.parse(localStorage.getItem('USER_TOKEN')).userInfo.username,
        password: this.validateForm.value.oldPW,
        new_password: this.validateForm.value.newPW
      }
      this.changePW.post('/v1/user/reset', obj).subscribe(res => {
        if (res['code'] === 200) {
          this.message.success('修改成功，请重新登录！', {
            nzDuration: 2000
          })
          // 注销
          this.user.logOut()
        }
      })
    }
  }
  ngOnInit() {
    this.validateForm = this.fb.group({
      oldPW: [null, [Validators.required]],
      newPW: [null, [Validators.required]],
      checkPW: [null, [Validators.required]],
    })
  }

}
